from django.conf import settings


def init_permission(user_obj, request):
    # 获取用户所有的权限
    permission_queryset = user_obj.roles.filter(permissions__url__isnull=False).values(
        "permissions__id",
        "permissions__url",
        "permissions__title",
        "permissions__name",
        "permissions__parent_id",
        "permissions__parent__name",
        "permissions__menu__id",
        "permissions__menu__icon",
        "permissions__menu__title",
    ).distinct()

    permission_dict = {}
    menu_dict = {}

    for row in permission_queryset:
        # 获取所有的权限
        permission_dict[row["permissions__name"]] = {
            "id": row['permissions__id'],
            "url": row['permissions__url'],
            "pid": row["permissions__parent_id"],
            "pname": row["permissions__parent__name"],
            "title": row["permissions__title"]
        }

        # 获取菜单id
        menu_id = row.get("permissions__menu__id")
        if not menu_id:
            continue

        if menu_id not in menu_dict:
            # 构造二级菜单的数据结构
            menu_dict[menu_id] = {
                "title": row['permissions__menu__title'],
                "icon": row['permissions__menu__icon'],
                "children": [
                    {"id": row["permissions__id"], "title": row['permissions__title'], "url": row['permissions__url']}
                ]
            }
        else:
            menu_dict[menu_id]['children'].append(
                {"id": row["permissions__id"], "title": row['permissions__title'], "url": row['permissions__url']})

    """
    二级菜单数据结构
    {
        1: {
            'title': '客户管理',
            'icon': 'fa-address-card-o',
            'children': [
                {'title': '客户列表','url': '/customer/list/'
            }]
        },
        2: {
            'title': '信息管理',
            'icon': 'fa-coffee',
            'children': [
                {'title': '账单列表', 'url': '/payment/list/'
            }]
        }
    }
    """

    # 用户信息和权限写入session中
    request.session['user_info'] = {
        "id": user_obj.id,
        "name": user_obj.username,
    }

    print(permission_dict)

    request.session[settings.PERMISSION_SESSION_KEY] = permission_dict
    request.session[settings.MENU_SESSION_KEY] = menu_dict
